<?php
class IndexAction extends HomeCommonAction {
    public function index() {
        import("ORG.Util.String");
        if($this->getMember()) {
            $this->assign('user', $this->getMember());
        }
        //活跃分享
        $Share = D('Share');
        $share_info = $Share->where()->order('count_view desc')->limit('0,6')->select();
        for($i=0;$i<count($share_info);$i++){
            $share_info[$i]['content'] = String::msubstr(strip_tags(html_entity_decode($share_info[$i]['content'])), $start=0, 150);
        }
		
        //流行问答
        $Question = D('Question');
        $question_info = $Question->where()->order('count_share desc')->limit('0,6')->select();        
        
        //活跃用户
        //        $UserHistory = D('UserHistory');
        $user_info_arr = $Share->field("count(id) as count ,userid")->where()->group('userid')->order('count desc')->limit('0,6')->select();
        $uid_arr = array(); 
        $User = D('User');
        foreach($user_info_arr as $user_info){
            
            $user_one =  $User->find($user_info['userid']);
            $uid_arr[] = $user_one;
        }
       
        
       
        
        //排行榜

        $share_order_info = $Share->relation('user')->where()->order('score desc')->limit('0,9')->select();
        for($i=0;$i<count($share_order_info);$i++){
        	$share_video = ubb($share_order_info[$i]['content']);
            $share_order_info[$i]['share_video'] = $share_video;
            $share_order_info[$i]['content'] = String::msubstr(strip_tags(html_entity_decode($share_order_info[$i]['content'])), $start=0, 200);
        }

        $Notice = D("Notice");
        $notice_info = $Notice->where('type = 0')->order('add_time desc')->limit('0,3')->select();

        $Ad = D("Ad");
        $ad_info = $Ad->where("type = 999")->order('id desc')->limit('0,6')->select();
        //        dump($ad_info);
        $rand_num = rand(0,count($ad_info)-1);
        
        $ad_info_0 = $ad_info['0'];
        $ad_info['0'] = $ad_info[$rand_num];
        $ad_info[$rand_num] = $ad_info_0;
        
        
        $this->assign('ad_info',$ad_info);
        
        $this->assign('user_info', $uid_arr);
        $this->assign('question_info',$question_info);
        $this->assign('share_info',$share_info);
        $this->assign('share_order_info',$share_order_info);
        $this->assign('notice_info',$notice_info);
		$this->kept_list();
        $this->display('index');
    }


    public function shareMessage() {
        import("ORG.Util.String");
        //最新分享
        $Share = D('Share');
        $share_info_new = $Share->relation('user')->where()->order('time_add desc')->limit('0,6')->select();
        for($i=0;$i<count($share_info_new);$i++){
        //            $share_info_new[$i]['content'] = String::msubstr($share_info_new[$i]['content'], $start=0, 100);
            $share_info_new[$i]['content'] =  "　　".msubstr($share_info_new[$i]['content'], 0, 90)."..."; //--codetaste
        }
        $this->assign('share_info_new',$share_info_new);
        $this->display('shareMessage');
    }
    
    public function questionMessage() {
        import("ORG.Util.String");
        $Question = D('Question');     

        $list = $Question->relation('user')->where()->order('time_add desc')->limit('0,6')->select();
        for($i=0;$i<count($list);$i++){
            $list[$i]['content'] = String::msubstr($list[$i]['content'], $start=0, 100);
        }
        $this->assign('list',$list);
        $this->display('questionMessage');
    }
    
    public function doLogin() {
        $session_name = Session::getLocal('user_name');
        if(!empty($session_name)){
            if($this->getMember()) {
                echo json_encode($this->getMember());
            }
            return true;
        }

        $user_name = trim($_POST['username']);
        $password = trim($_POST['password']);
        if(empty ($user_name)) {echo 0;return false;}
        if(empty($password)) {echo 0;return false;}
        //		echo $_POST['verify'];die;
        //		if($_SESSION['verify'] != md5($_POST['verify'])) {
        //		    echo 0;return false;
        //		}
        $User = D('user');
        $user = $User->where("user_name = '{$user_name}' and password = '".md5($password)."'")->find();
        if(count($user)<=0) {echo 0;return false;}
        if($user['status'] == '0'){echo 2;return false;}
        Session::setLocal('user_name', $user['user_name']);
        Session::setLocal('nickname', $user['nickname']);
        Session::setLocal('id', $user['id']);
        Session::setLocal('user', 1);
        if($this->getMember()) {
            echo json_encode($this->getMember());
        }
        return true;
    }

    public function verify() {
        import("ORG.Util.Image");
        Image::buildImageVerify();
    }

    public function regedit() {
    	import("ORG.Util.String");
        $data['user_name'] = $_POST['username'];
        $data['password'] = md5($_POST['psd']);
        $data['email'] = $_POST['email'];
        $User = D('User');
        $user_info = $User->where("user_name = '{$data['user_name']}'")->find();
        
        $result = array();
        if(count($user_info)>0) {$result['ret'] = 3;}
        
        // 随机出一组字符串用户用户激活
        $data['active_code'] = String::rand_string(32);
        $rs = $User->add($data);
        $title = '请激活你的账号，完成注册。';
        $domain = C('DOMAIN');
        $msg = "亲爱的{$data['user_name']}：<br/> &nbsp;&nbsp;&nbsp;&nbsp;欢迎加入品购网! 你的用户名为{$data['user_name']}；密码为{$_POST['psd']}。<br/>
               &nbsp;&nbsp;&nbsp;&nbsp;请点击下面的链接完成注册： <a href='{$domain}/Home/Index/active/uuid/{$rs}/code/{$data['active_code']}'>{$domain}/Home/Index/uuid/{$rs}/code/{$data['active_code']}</a><br/>
               &nbsp;&nbsp;&nbsp;&nbsp;如果以上链接无法点击，请将上面的地址复制到你的浏览器(如IE)的地址栏进入品购360pick。  <br/>
               &nbsp;&nbsp;&nbsp;&nbsp;--品购网 <br/>
               &nbsp;&nbsp;&nbsp;&nbsp;(这是一封自动产生的email，请勿回复。)";

//        激活链接:<a href="'.$domain.'/Home/Index/active/uuid/'.$rs.'/code/'.$data['active_code'].'">'.$domain.'/Home/Index/uuid/'.$rs.'/code/'.$data['active_code'].'</a>';
        jMail($data['email'], $title, $msg);
        if($rs) {
            echo 1;
        } else {
            echo 2;
        }
        return true;
    }
    public function active() {
    	$data['id'] = $_GET['uuid'];
    	$data['active_code'] = $_GET['code'];
    	
    	$User = d('User');
    	$user = $User->where("id = '{$data['id']}' and active_code = '{$data['active_code']}'");
    	$user_info = $user->find();
    	if ($user_info) {
    		$data['status'] = 1;
    		$user->save($data);
    		Session::setLocal('user_name', $user_info['user_name']);
	        Session::setLocal('nickname', $user_info['nickname']);
	        Session::setLocal('id', $user_info['id']);
	        Session::setLocal('user', 1);
    	}
    	header("Location: ".__APP__."/Home/Index");
    	
    	// 跳转到首页
    	$this->display('active');
    }

	/* 什么值得买二次开发首页查询调用列表开始*/
	private function kept_list(){
	    
		$sql = M("kept");
		import("ORG.Util.Page");
		$where['is'] = array('eq',1);
		$count      = $sql->where($where)->count();
		$Page       = new Page($count,C('KEPT_PAGE'));
		$show       = $Page->show();
		$show2       = $Page->show2();
		$list = $sql->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		$i=-1;
		foreach ($list as $key =>$value){
			$i++;
			$User = M("User");
			$condition['id'] = $value['userid'];
			$arr=$User->where($condition)->select();
			$list[$i]['user']=$arr[0]["user_name"];
			$sql2=M('Kept_comments');
			$wheres['typeid']=$value['id'];
			$wheres['is']=1;
			$row=$sql2->where($wheres)->count();
			$list[$i]['comments']=$row;
			//$list[i]['user']=$arr[0]["user_name"];
		}
		$this->assign('kept_list',$list);
		$this->assign('page',$show);
		$this->assign('page2',$show2);
	}//调用列表
	function login(){
		if($this->is_login()){
			$this->display("kept_form");
		}else{
			$this->display();
		}//判断是否登录，没有登录加载登录界面，登录加载表单页面
	}//获取AJAX是登录界面还是填写表单界面

	function reg(){
		if($this->is_login()){
			$this->display("kept_form");
		}else{
			$this->display();
		}//判断是否登录，登录后不用注册，没有登录直接注册界面
	}

	private function  is_login(){
	    $session_name = Session::getLocal('user_name');
		if(!empty($session_name)){
			return true;
		}
	}//请把登录判断限制写在这儿如果登录成功请返回true否则返回$is_login为false;

	function post(){
		//$_POST['title']."|".$_POST['url']."|".$_POST['laiyuan']."|".$_POST['liyou'];
		switch ($_POST['name']){
			case 'kept' :
				$data=array();
				$data['title'] =$_POST['title'];
				$data['url'] = $_POST['url'];
				$data['source'] =$_POST['laiyuan'];
				$str=str_replace("\n", "<br>", str_replace(" ", "&nbsp;", $_POST['liyou']));//把内容空格分行替换网页代码
				$data['con'] =$str;
				$data['is'] =C('KEPT_IS');
				$userid=$this->getMember();
				$data['userid']=$userid[id]; //请获取登录用户的ID值
				$data['data']=time();
				if($this->insert($_POST['name'],$data)){
					echo 1;
				}else{
					echo 0;
				};
				break;
			case 'kept_comments':
				$data=array();
				$data['typeid'] =$_POST['get'];
				$userid=$this->getMember();
				$data['userid'] = $userid[id];
				$str=str_replace("\n", "<br>", $_POST['con']);//把内容空格分行替换网页代码
				$data['con'] = $str;
				$data['is']=C('COMMENTS_IS');
				$data['data']=time();
				if($this->insert($_POST['name'],$data)){
					echo 1;
				}else{
					echo 0;
				};
				break;
		}
	}//提交判断
	private function insert($m,$data){
		//print_r($data);
		$sql = M($m);
		if($sql->add($data)){
			return true;
		}else{
			return false;
		}
	}
	function kept_con(){
		$sql = M("kept");
		$where['id']=$_GET['id'];
		$get['id']=array('lt',$_GET['id']);
		$get['is']=1;
		$pr['id']=array('gt',$_GET['id']);
		$pr['is']=1;
		$arr=$sql->where($where)->select();
		$next=$sql->where($get)->order('id desc')->find();
		$pro=$sql->where($pr)->order('id asc')->find();
		//print_r($next);
		//echo "<br>";
		//print_r($pro);
		$User = M("User");
	    $condition['id'] =$arr[0]['userid'];
	    $row=$User->where($condition)->select();
	    $arr[0]['user']=$row[0]['user_name'];
	    $sql2 = M("kept_comments");
		import("ORG.Util.Page");
		$wheres['typeid']=$_GET['id'];
		$wheres['is']=1;
		$count      = $sql2->where($wheres)->count();
		$arr[0]['num']=$count;
		$Page       = new Page($count,C('COMMENTS_PAGE'));
		$show       = $Page->show();
		$list = $sql2->where($wheres)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		$i=count($list);
		$a=1;
		
		foreach ($list as $key =>$value){
			$list[$a-1]['uid']=$i;
			$i--;
			$a++;
			$User2 = M("User");
			$condition2['id'] = $value['userid'];
			$arr2=$User2->where($condition2)->select();
			$list[$a-2]['user']=$arr2[0]["user_name"];
			if($arr2[0]["user_photo"]!==''){
			$list[$a-2]['user_photo']=$arr2[0]["user_photo"];
			}else{
				$list[$a-2]['user_photo']='/Public/images/user_photo.jpg';
			}
			
		}
		//上一篇下一篇赋值模版
		if($next){
		   $this->assign('next',$next);
		}
		if($pro){
			$this->assign('pr',$pro);
		}
		//上一篇下一篇赋值模版End
		$this->assign('arr',$arr);
		$this->assign("p_list",$list);
		$this->assign('page',$show);
		$this->display();
	}
	function hit(){
		$sql=M('kept');
		$sql->setInc('hit','id='.$_GET['id']); 
	}//访问写入
	/* 什么值得买二次开发首页查询调用列表End*/
}
?>
